<template>
  <div>
    <el-form label-width="80px" :model="roleData" :rules="rules" ref="roleForm">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleData.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色权限" prop="permission">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          node-key="path"
          @check-change="handleCheck"
          ref="tree"
          show-checkbox
        >
        </el-tree>
      </el-form-item>
      <el-form-item>
        <el-button
          :type="row ? 'success' : 'primary'"
          size="default"
          @click="handleSubmit"
        >
          {{ row ? "修改" : "新增" }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { children } from "@/router/index";
import { rolePost, rolePut } from "@/api/user";
export default {
  props: ["row"],
  data() {
    var checkPermission = (rule, value, callback) => {
      if (value.length == 0) {
        return callback(new Error("必须勾选至少一个权限"));
      }
      return callback(); //验证通过
    };
    return {
      treeData: children,
      defaultProps: {
        label: (data) => data.meta.title,
      },
      roleData: {
        roleName: "",
        permission: [],
      },
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        permission: [
          {
            validator: checkPermission,
            message: "请选择角色权限",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    handleCheck() {
      let checkedKeys = this.$refs.tree.getCheckedKeys(); //获取被勾选的tree的path
      // console.log(checkedKeys);
      this.roleData.permission = checkedKeys;
    },
    handleSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          // console.log(this.roleData);
          if (this.row) {
            let { objectId } = this.row;
            rolePut(objectId, this.roleData).then((res) => {
              this.$emit("update:table", { ...this.roleData, objectId });
            }); //更新
          } else {
            rolePost(this.roleData).then((res) => {
              let { objectId } = res.data;
              this.$emit("update:table", { ...this.roleData, objectId });
            }); //新增
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  mounted() {
    console.log("角色弹窗显示了");
    if (this.row) {
      let { roleName, permission } = this.row;
      this.roleData.roleName = roleName;
      this.$refs.tree.setCheckedKeys(permission);
    }
  },
};
</script>
